package com.example.common.Interface.user.entity.vo;

import com.example.common.response.BizException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class CreditCardInfoVO {
    private String creditCardNumber;
    private int creditCardCvv;
    private int creditCardExpirationYear;
    private int creditCardExpirationMonth;

    public boolean isValidCreditCard() {
        // 检查信用卡号码是否有效
        String creditCardNumber = this.getCreditCardNumber();
        if (creditCardNumber == null || creditCardNumber.length() != 16) {
            return false;
        }
        for (int i = 0; i < creditCardNumber.length(); i++) {
            if (!Character.isDigit(creditCardNumber.charAt(i))) {
                return false;
            }
        }
        // 检查信用卡CVV是否有效
        int creditCardCvv = this.getCreditCardCvv();
        if (creditCardCvv < 100 || creditCardCvv > 999) {
            return false;
        }
        // 检查信用卡到期日期是否有效
        int creditCardExpirationYear = this.getCreditCardExpirationYear();
        int creditCardExpirationMonth = this.getCreditCardExpirationMonth();
        if (creditCardExpirationYear < 2023 || creditCardExpirationYear > 2030) {
            return false;
        }
        if (creditCardExpirationMonth < 1 || creditCardExpirationMonth > 12) {
            return false;
        }
        return true;
    }

    public String serialize() {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.writeValueAsString(this);
        }catch (Exception e){
            throw new BizException("序列化失败");
        }
    }

    // 反序列化方法，将 JSON 字符串转换为对象
    public static CreditCardInfoVO deserialize(String json) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.readValue(json, CreditCardInfoVO.class);
        }catch (Exception e){
            throw new BizException("反序列化失败");
        }
    }
}